package com.happy3w.cmds.utils;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class XmlUtil {
    public static Document loadXml(String xmlFile) {
        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            return dBuilder.parse(xmlFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static NodeList getElements(Element element, String path) {
        NodeList nodes = null;
        Element current = element;
        for (String name : path.split("/")) {
            if (current == null) {
                return null;
            }
            nodes = current.getElementsByTagName(name);
            if (nodes.getLength() == 0) {
                return null;
            }
            current = nodes.getLength() == 0 ? null : (Element) nodes.item (0);
        }
        return nodes;
    }

    public static String getText(Element element, String path) {
        Element current = element;
        for (String name : path.split("/")) {
            NodeList subElements = current.getElementsByTagName(name);
            if (subElements.getLength() == 0) {
                return null;
            }
            current = (Element) subElements.item(0);
        }
        return current.getTextContent();
    }

    public static Stream<Element> elements(NodeList modules) {
        if (modules == null) {
            return Stream.empty();
        }
        return IntStream.range(0, modules.getLength())
                .mapToObj(modules::item)
                .filter(node -> node instanceof Element)
                .map(node -> (Element) node);
    }
}
